
import sqlite3
from constant import Constants
from .das.database_pool import DatabasePool

# 初始化监控系统表结构


def checkAndInitDB():
    table_name = "ant_monitor_stock"
    # 检查表是否存在
    if not check_table_exists(table_name):
        print(f"表 '{table_name}' 不存在，正在创建...")
        init_db()
    else:
        print(f"表 '{table_name}' 已存在。")


def check_table_exists(table_name):
    """检查指定表是否存在"""
    db_pool = DatabasePool(max_connections=1)
    cursor = db_pool.connect().cursor()
    cursor.execute(f'''
        SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}';
    ''')
    table_exists = cursor.fetchone() is not None
    cursor.close()
    return table_exists
# 初始化所有的SQL


def init_db():
    db_pool = DatabasePool(max_connections=1)
    conn = db_pool.connect()
    cursor = conn.cursor()
    try:
        # 读取 SQL 文件
        sql_file = "./resources/base.sql"
        with open(sql_file, 'r', encoding='utf-8') as f:
            sql_script = f.read()

        # 分割 SQL 语句并执行
        for statement in sql_script.split(';'):
            statement = statement.strip()
            if statement:  # 确保不是空语句
                cursor.execute(statement)

        # 提交事务
        conn.commit()
        print("所有 SQL 语句执行成功！")

    except sqlite3.Error as e:
        print(f"执行 SQL 时发生错误: {e}")

    finally:
        # 关闭游标和连接
        cursor.close()
        conn.close()
